package work.jame.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import work.jame.blog.framework.utils.DateTimeUtils;
import work.jame.blog.pojo.UserLoginLog;
import work.jame.blog.mapper.UserLoginLogMapper;
import work.jame.blog.service.UserLoginLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Jame
 * @since 2023-05-15
 */
@Service
public class UserLoginLogServiceImpl extends ServiceImpl<UserLoginLogMapper, UserLoginLog> implements UserLoginLogService {

    @Override
    public boolean queryUserLoggedInFromIp(Long userId, String ip) {
        QueryWrapper<UserLoginLog> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("login_ip", ip);
        return this.count(wrapper) > 0;
    }

    @Override
    public String queryLastTimeLoginIpAddress(Long userId, String ip) {
        QueryWrapper<UserLoginLog> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("login_ip", ip)
                .orderByDesc("insert_time");
        Page<UserLoginLog> page = new Page<>(1, 1);
        Page<UserLoginLog> result = this.page(page, wrapper);
        if (result.getTotal() != 1) {
            return null;
        }
        return result.getRecords().get(0).getAddress();
    }

    @Override
    public boolean queryUserToDayLogin(Long userId) {
        QueryWrapper<UserLoginLog> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .ge("insert_time", DateTimeUtils.getTodayStartTime())
                .le("insert_time", DateTimeUtils.getTodayEndTime());
        return this.count(wrapper) > 0;
    }


}
